package com.sgb.kjwl.view.ui.activity.packers;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLaborServiceAndEmploymentBinding;
import com.sgb.kjwl.model.entity.packers.LabourServiceAndEmploymentEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.utils.TextViewUtils;
import com.sgb.kjwl.view.ui.activity.self.packers.LaborServiceAndEmploymentPublishActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.packers.LaborServiceAndEmploymentAdapter;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.packers.LaborServiceAndEmploymentViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.helper.OnMultiClickListener;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author younghow
 * @date 2021/7/5
 * description:劳务用工列表页
 */
public class LaborServiceAndEmploymentActivity extends AppActivity {

    ActivityLaborServiceAndEmploymentBinding mBinding;
    LaborServiceAndEmploymentAdapter mAdapter;
    LaborServiceAndEmploymentViewModel mViewModel;
    ThreeLevelAreaWindow mWorkType;
    ThreeLevelAreaWindow mWorkAddress;
    private final String mWorkAddressName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME, "");
    private String mOneLevelName = "";
    private String mTwoLevelName = "";
    private String mThreeLevelName = "";
    private String mProvinceName;
    private String mCityName = "";
    private String mAreaName = "";
    private String mProvinceNo;
    private String mCityNo = "";
    private final List<String> mAreaNo = new ArrayList<>();
    private String mIndustryNo = "";
    private String mCategoryNo = "";
    private String mWorkNo = "";
    private int page = 0;
    private boolean isLoadMore;
    private String isInit;
    private LabourServiceAndEmploymentEntity labourServiceAndEmploymentEntity;


    @Override
    protected void initView() {
        super.initView();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_labor_service_and_employment);
        mBinding.setLifecycleOwner(this);
        if (!TextUtils.isEmpty(mProvinceName)) {
            mBinding.tvWorkAddress.setText(mProvinceName);
        }
        mViewModel = new ViewModelProvider(this).get(LaborServiceAndEmploymentViewModel.class);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setMenuFunctionClick(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    ActivityJump.jumpToActivityForResult(LaborServiceAndEmploymentActivity.this, LaborServiceAndEmploymentPublishActivity.class, 0);
                }
            }
        });

        initData();
        initPopWindow();
        initLiveData();
        initRecyclerView();
        initButton();
    }

    private void initButton() {
        mBinding.tvWorkType.setOnClickListener(this);
        mBinding.tvWorkAddress.setOnClickListener(this);
    }

    private void initData() {
        mProvinceNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mProvinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");
        isInit = "Y";
        mViewModel.getCityList();
        mViewModel.getLinkAgeWorkType();
        loadComData(false);
    }


    private void initPopWindow() {
        mWorkType = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                mOneLevelName = baseAreaEntity.getName();
                if (!mIndustryNo.equals(baseAreaEntity.getNo())){
                    mCategoryNo = "";
                    mWorkNo = "";
                    mTwoLevelName = "";
                    mThreeLevelName = "";
                }
                mIndustryNo = baseAreaEntity.getNo();
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                mTwoLevelName = baseAreaEntity.getName();
                if (!mCategoryNo.equals(baseAreaEntity.getNo())){
                    mWorkNo = "";
                    mThreeLevelName = "";
                }
                mCategoryNo = baseAreaEntity.getNo();
            }

            @Override
            protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                mThreeLevelName = baseAreaEntity.getName();
                mWorkNo = baseAreaEntity.getNo();
            }

            @Override
            protected void reset() {
                super.reset();
                mWorkType.dismiss();
                mWorkType.setDefaultForPosition(0);
                loadComData(false);
            }
        };
        mWorkType.setBgView(mBinding.grayLayout);
        mWorkType.setThreeListIsGone(false);
        mWorkType.setProvinceSingle();
        mWorkType.setCitySingle();
        mWorkType.setAreaSingle();
        mWorkType.setThreeListIsGone(false);
        mWorkType.setOnResultClick((key1, key2, key3) -> {
            isInit = "N";
            loadComData(false);
        });
        mWorkType.setOnDismissListener(() -> {
            TextViewUtils.changeTextView(this, mBinding.tvWorkType, R.mipmap.ic_down_arrow_red, R.mipmap.ic_down_arrow_u, R.mipmap.ic_down_arrow_n,
                    !getString(R.string.app_all).equals(mOneLevelName) && !"".equals(mOneLevelName), false, R.color.color_EF4033, R.color.color_333333);

            if (!getString(R.string.app_all).equals(mThreeLevelName) && !"".equals(mThreeLevelName)) {
                mBinding.tvWorkType.setText(mThreeLevelName);
                return;
            } else {
                mBinding.tvWorkType.setText(mTwoLevelName);
            }

            if (!getString(R.string.app_all).equals(mTwoLevelName) && !"".equals(mTwoLevelName)) {
                mBinding.tvWorkType.setText(mTwoLevelName);
                return;
            } else {
                mBinding.tvWorkType.setText(mOneLevelName);
            }

            if (!getString(R.string.app_all).equals(mOneLevelName) && !"".equals(mOneLevelName)) {
                mBinding.tvWorkType.setText(mOneLevelName);
            } else {
                mBinding.tvWorkType.setText("工种名称");
            }
        });

        mWorkAddress = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                mProvinceName = baseAreaEntity.getSimpleName();
                if (!mProvinceNo.equals(baseAreaEntity.getId())){
                    mCityNo = "";
                    mAreaNo.clear();
                    mCityName = "";
                    mAreaName = "";
                }
                mProvinceNo = baseAreaEntity.getId();
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                if (!mCityNo.equals(baseAreaEntity.getId())){
                    mAreaNo.clear();
                    mAreaName = "";
                }
                mCityNo = baseAreaEntity.getId();
                mCityName = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                super.areaClick(baseAreaEntity, position);
                mAreaName = baseAreaEntity.getSimpleName();
                mAreaNo.clear();
                if (!"".equals(baseAreaEntity.getNo())){
                    mAreaNo.add(baseAreaEntity.getNo());
                }
            }

            @Override
            protected void reset() {
                super.reset();
                mWorkAddress.dismiss();
                mWorkAddress.setDefaultForPosition(0);
                loadComData(false);
            }
        };
        mWorkAddress.setBgView(mBinding.grayLayout);
        mWorkAddress.setThreeListIsGone(false);
        mWorkAddress.setProvinceSingle();
        mWorkAddress.setCitySingle();
        mWorkAddress.setAreaSingle();
        mWorkAddress.setThreeListIsGone(false);
        mBinding.tvWorkAddress.setText(mProvinceName);
        TextViewUtils.changeTextView(this, mBinding.tvWorkAddress, R.mipmap.ic_down_arrow_red, R.mipmap.ic_down_arrow_u, R.mipmap.ic_down_arrow_n,
                !"".equals(mProvinceName), false, R.color.color_EF4033, R.color.color_333333);
        mWorkAddress.setOnResultClick((key1, key2, key3) -> {
            isInit = "N";
            loadComData(false);
        });
        mWorkAddress.setOnDismissListener(() -> {
            TextViewUtils.changeTextView(this, mBinding.tvWorkAddress, R.mipmap.ic_down_arrow_red, R.mipmap.ic_down_arrow_u, R.mipmap.ic_down_arrow_n,
                    !"".equals(mProvinceName), false, R.color.color_EF4033, R.color.color_333333);

            if (!getString(R.string.app_all).equals(mAreaName) && !"".equals(mAreaName)) {
                mBinding.tvWorkAddress.setText(mAreaName);
                return;
            } else {
                mBinding.tvWorkAddress.setText(mCityName);
            }

            if (!getString(R.string.app_all).equals(mCityName) && !"".equals(mCityName)) {
                mBinding.tvWorkAddress.setText(mCityName);
                return;
            } else {
                mBinding.tvWorkAddress.setText(mProvinceName);
            }

            if (!getString(R.string.app_all).equals(mProvinceName) && !"".equals(mProvinceName)) {
                mBinding.tvWorkAddress.setText(mProvinceName);
            } else {
                if (!getString(R.string.app_all).equals(mProvinceName)) {
                    mBinding.tvWorkAddress.setText(mWorkAddressName);
                } else {
                    mBinding.tvWorkAddress.setText(getString(R.string.app_all));
                }
            }
        });
    }

    private void loadComData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        if (isLoadMore){
            page++;
        }else {
            page = 1;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("industryNo",mIndustryNo);
        map.put("categoryNo",mCategoryNo);
        map.put("workNo",mWorkNo);
        map.put("provinceNo",mProvinceNo);
        map.put("cityNo",mCityNo);
        map.put("areaNo",mAreaNo);
        map.put("limit",15);
        map.put("page",page);
        if ("Y".equals(isInit)){
            map.put("isInit",isInit);
        }
        mViewModel.getLabourList(map);
    }

    private void initLiveData() {
        mViewModel.loadingLiveData.observe(this, aBoolean -> DialogHelper.showProgressDialog(LaborServiceAndEmploymentActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));
        mViewModel.successLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());
        mViewModel.errorLiveData.observe(this, aBoolean -> DialogHelper.dismissProgressDialog());

        mViewModel.mAreaLiveData.observe(this, addressEntities -> mWorkAddress.setDataForAll(addressEntities, true, SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE, "")));

        mViewModel.mServiceLiveData.observe(this, labourServiceAndEmploymentEntities -> {
            if (isLoadMore) {
                if (labourServiceAndEmploymentEntities != null && labourServiceAndEmploymentEntities.size() > 0) {
                    mAdapter.addDatas(labourServiceAndEmploymentEntities);
                }
                if (labourServiceAndEmploymentEntities != null) {
                    mBinding.recyclerView.setNoMore(labourServiceAndEmploymentEntities.size() < 10);
                }
                mBinding.recyclerView.setVisibility(View.VISIBLE);
            } else {
                mBinding.recyclerView.refreshComplete();
                if (labourServiceAndEmploymentEntities != null && labourServiceAndEmploymentEntities.size() > 0) {
                    mBinding.emptyView.setVisibility(View.GONE);
                    mAdapter.setDatas(labourServiceAndEmploymentEntities);
                    mBinding.recyclerView.smoothScrollToPosition(0);
                    if (labourServiceAndEmploymentEntities.size() < NumberConstant.NUMBER_TEN) {
                        mBinding.recyclerView.setNoMore(true);
                    }
                } else {
                    mAdapter.clearDatas();
                    mBinding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });

        mViewModel.mCityData.observe(this, addressEntities -> mWorkAddress.setDataForAll(addressEntities,true,SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"")));
        mViewModel.mWorkTypeData.observe(this, addressEntities -> mWorkType.setDataForAllTeam(addressEntities,true,""));

        mViewModel.mLaborWorkLiveData.observe(this, laborWorkMomentDetailEntity -> {
            if (laborWorkMomentDetailEntity.getIsEnable() == 0) {
                MToast.showToast(LaborServiceAndEmploymentActivity.this,"该劳务用工已招满，请重新选择");
                loadComData(false);
            }else {
                ActivityJump.jumpToActivityForResult(LaborServiceAndEmploymentActivity.this,LaborServiceAndEmploymentDetailActivity.class,0, Pair.create("no",labourServiceAndEmploymentEntity.getNo()),Pair.create("workNo",labourServiceAndEmploymentEntity.getWorkNo()),Pair.create("workName",labourServiceAndEmploymentEntity.getCategoryName()),Pair.create("isFocus",labourServiceAndEmploymentEntity.getIsFocus()),Pair.create("isApply",labourServiceAndEmploymentEntity.isApply()),Pair.create("mMomentNo",labourServiceAndEmploymentEntity.getUserNo()),Pair.create("workNameForList",labourServiceAndEmploymentEntity.getWorkName()),Pair.create("employmentType",labourServiceAndEmploymentEntity.getEmploymentType()),Pair.create("imId",labourServiceAndEmploymentEntity.getImId()));
            }
        });
    }

    private void initRecyclerView() {
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp10);
            }
        });
        mAdapter = new LaborServiceAndEmploymentAdapter(this, null);
        mBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClick(new AdapterOnItemClick<LabourServiceAndEmploymentEntity>() {
            @Override
            public void onItemClick(LabourServiceAndEmploymentEntity labourServiceAndEmploymentEntity, int position) {
                LaborServiceAndEmploymentActivity.this.labourServiceAndEmploymentEntity = labourServiceAndEmploymentEntity;
                mViewModel.getLaborWorkDetail(labourServiceAndEmploymentEntity.getNo());
            }
        });

        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadComData(false);
            }

            @Override
            public void onLoadMore() {
                loadComData(true);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.tv_work_type) {
            TextViewUtils.changeTextView(this, mBinding.tvWorkType, R.mipmap.ic_down_arrow_red, R.mipmap.ic_down_arrow_u, R.mipmap.ic_down_arrow_n,
                    false, true, R.color.color_EF4033, R.color.color_333333);
            showWorkType();
        } else if (id == R.id.tv_work_address) {
            TextViewUtils.changeTextView(this, mBinding.tvWorkAddress, R.mipmap.ic_down_arrow_red, R.mipmap.ic_down_arrow_u, R.mipmap.ic_down_arrow_n,
                    false, true, R.color.color_EF4033, R.color.color_333333);
            showWorkAddress();
        }
    }


    private void showWorkAddress() {
        mWorkAddress.showPopwindow(mBinding.llLaborService,0,0);
    }

    private void showWorkType() {
        mWorkType.showPopwindow(mBinding.llLaborService,0,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2 || resultCode == 1){
            loadComData(false);
        }
    }
}
